package frame.jserialcomm;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.fazecast.jSerialComm.SerialPort;
import ntd.util.UtilThreadPool;
import ntd.util.config.common.exception.ComException;
import ntd.util.fun.ComFun;

import java.util.List;

public class ToolJSerialComm {

    private SerialPort selectedPort;

    /**
     * 初始化
     * @param com
     * @param funIn
     */
    public ToolJSerialComm(String com, int baudRate, ComFun.FunIn<String> funIn) {
        // 获取可用的串口列表
        SerialPort[] ports = SerialPort.getCommPorts();
        List<String> portNames = CollStreamUtil.toList(CollectionUtil.newArrayList(ports), SerialPort::getSystemPortName);

        if (!CollectionUtil.contains(portNames, com)) {
            throw new ComException("该com口[{}]不可用", com);
        }

        // 选择要连接的串口
        selectedPort = SerialPort.getCommPort(com);

        // 配置串口参数
        selectedPort.setComPortParameters(baudRate, 8, 1, SerialPort.NO_PARITY);

        if (!selectedPort.openPort()) {
            throw new ComException("com口[{}]打开失败", com);
        }

        UtilThreadPool.periodRun(() -> {
            if (ObjectUtil.isNotNull(funIn)) {
                byte[] readBuffer = new byte[1024];
                int numRead = selectedPort.readBytes(readBuffer, readBuffer.length);
                String receivedData = new String(readBuffer, 0, numRead);
                funIn.accept(receivedData);
            }
        }, 1000);
    }

    /**
     * 消息推送
     * @param buffer
     */
    public void putMsg(byte[] buffer) {
        StaticLog.info("串口推送数据[{}][{}]", buffer, JSONUtil.toJsonStr(buffer));
        selectedPort.writeBytes(buffer, buffer.length);
    }

    /**
     * 关闭串口
     */
    public void close() {
        // 关闭串口
        selectedPort.closePort();
    }

}
